package cn.edu.bit.mm;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.edu.bit.mm.service.SearchService;
import cn.edu.bit.dto.WebPage;

/**
 * 
 * @author maomao
 *	这下好了连servlet都不用了,以后连struts都不用了
 */
public class Searching implements SearchAction {
	

	@Autowired
	@Qualifier("singleDaemonSearchService")
	private SearchService service;	

	
	public void execute(HttpServletRequest request, HttpServletResponse response,ServletContext servletContext)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");		
		HttpSession session = request.getSession();		
		String keyWord = request.getParameter("keyWord");		
		String pageNumberReq = request.getParameter("pageNumber");
		
		if(!service.checkKeyWord(keyWord)){
			returnToIndex(request, response,servletContext);
			return;
		}
		
			
		int pageNumber = service.computeQueryPage(pageNumberReq);
		
		WebPage[] result = service.getSearchResult(keyWord, pageNumber);
		
		if(result == null){
			returnToIndex(request, response,servletContext);
			return;
		}
	
		session.setAttribute("result", result);
		if(pageNumber==1){
			session.setAttribute("totalPage", service.getTotalPage());
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append("/Response.jsp?currentPage=");
		sb.append(pageNumber);
		sb.append("&");
		sb.append("keyWord=");
		sb.append(keyWord);	
		sb.append("&");
		sb.append("isAllowed=");
		sb.append(101);	
		servletContext.getRequestDispatcher(sb.toString()).forward(request, response);
	   
		}

	private void returnToIndex(HttpServletRequest request,
			HttpServletResponse response,ServletContext servletContext) throws ServletException, IOException {
		servletContext.getRequestDispatcher("/index.html").forward(request, response);
		return;
	}
	
	public void setService(SearchService service) {
		this.service = service;
	}

}
